package com.study.hzpxlstovcf;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

public class App extends Application {

    private Label statusLabel = new Label("请选择一个 .xls 文件进行转换");
    private File lastSavedFile = null;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("XLS 转 VCF 工具");

        // 创建上传按钮并添加样式
        Button uploadButton = new Button("📁 选择 .xls 文件");
        uploadButton.setStyle(
                "-fx-font-size: 16px; " +
                        "-fx-padding: 10px 20px; " +
                        "-fx-background-color: #4CAF50; " +
                        "-fx-text-fill: white; " +
                        "-fx-background-radius: 5px; " +
                        "-fx-border-radius: 5px; " +
                        "-fx-cursor: hand;"
        );
        uploadButton.setOnAction(e -> handleFileUpload(primaryStage));

        // 创建打开文件夹按钮
        Button openFolderButton = new Button("📂 打开保存路径");
        openFolderButton.setStyle(
                "-fx-font-size: 16px; " +
                        "-fx-padding: 10px 20px; " +
                        "-fx-background-color: #2196F3; " +
                        "-fx-text-fill: white; " +
                        "-fx-background-radius: 5px; " +
                        "-fx-border-radius: 5px; " +
                        "-fx-cursor: hand;"
        );
        openFolderButton.setOnAction(e -> openSaveFolder());
        openFolderButton.setDisable(true);

        // 创建打开文件按钮
        Button openFileButton = new Button("📄 打开文件");
        openFileButton.setStyle(
                "-fx-font-size: 16px; " +
                        "-fx-padding: 10px 20px; " +
                        "-fx-background-color: #FF9800; " +
                        "-fx-text-fill: white; " +
                        "-fx-background-radius: 5px; " +
                        "-fx-border-radius: 5px; " +
                        "-fx-cursor: hand;"
        );
        openFileButton.setOnAction(e -> openSavedFile());
        openFileButton.setDisable(true);

        // 设置状态标签样式
        statusLabel.setWrapText(true);
        statusLabel.setStyle(
                "-fx-font-size: 14px; " +
                        "-fx-text-alignment: center; " +
                        "-fx-padding: 10px;"
        );

        // 创建垂直布局容器
        VBox root = new VBox(20);
        root.setPadding(new Insets(30));
        root.setAlignment(Pos.CENTER);
        root.setStyle(
                "-fx-background-color: #f5f5f5;"
        );

        // 添加标题标签
        Label titleLabel = new Label("Excel 转 vCard 联系人工具");
        titleLabel.setStyle(
                "-fx-font-size: 24px; " +
                        "-fx-font-weight: bold; " +
                        "-fx-text-fill: #333333;"
        );

        root.getChildren().addAll(titleLabel, uploadButton, openFolderButton, openFileButton, statusLabel);

        Scene scene = new Scene(root, 500, 350);
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    private void handleFileUpload(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("Excel 文件 (*.xls)", "*.xls")
        );
        File xlsFile = fileChooser.showOpenDialog(stage);

        if (xlsFile == null) {
            statusLabel.setText("未选择文件。");
            statusLabel.setStyle("-fx-text-fill: #333333; -fx-font-size: 14px;");
            return;
        }

        statusLabel.setText("正在读取文件: " + xlsFile.getName());
        statusLabel.setStyle("-fx-text-fill: #FF9800; -fx-font-size: 14px;");

        try {
            List<Contact> contacts = readContactsFromXls(xlsFile);
            if (contacts.isEmpty()) {
                statusLabel.setText("文件中没有读取到有效联系人数据。");
                statusLabel.setStyle("-fx-text-fill: #F44336; -fx-font-size: 14px;");
                return;
            }

            File vcfFile = chooseSaveVcfFile(stage);
            if (vcfFile == null) {
                statusLabel.setText("未选择保存位置。");
                statusLabel.setStyle("-fx-text-fill: #333333; -fx-font-size: 14px;");
                return;
            }

            writeVcfFile(contacts, vcfFile);
            lastSavedFile = vcfFile;
            statusLabel.setText("✅ 转换完成！\n已保存至:\n" + vcfFile.getAbsolutePath());
            statusLabel.setStyle("-fx-text-fill: #4CAF50; -fx-font-size: 14px;");

            // 启用打开文件夹和打开文件按钮
            enableActionButtons(true);

        } catch (Exception e) {
            e.printStackTrace();
            statusLabel.setText("❌ 转换失败: " + e.getMessage());
            statusLabel.setStyle("-fx-text-fill: #F44336; -fx-font-size: 14px;");
            enableActionButtons(false);
        }
    }

    private List<Contact> readContactsFromXls(File file) throws IOException {
        List<Contact> contacts = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file);
             HSSFWorkbook workbook = new HSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            boolean firstRow = true;

            for (Row row : sheet) {
                if (firstRow) {
                    firstRow = false;
                    continue;
                }

                String name = getStringValue(row.getCell(0));
                String phone = getStringValue(row.getCell(1));
                String gender = getStringValue(row.getCell(2)); // 新增：性别
                String title = getStringValue(row.getCell(3));
                String org = getStringValue(row.getCell(4));   // 单位是第5列（索引4）

                // 至少需要姓名和电话
                if ((name == null || name.trim().isEmpty()) &&
                        (phone == null || phone.trim().isEmpty())) {
                    continue;
                }

                contacts.add(new Contact(name, phone, org, title, gender));
            }
        }
        return contacts;
    }


    private String getStringValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 数字类字段如电话号码、工号等
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    private File chooseSaveVcfFile(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("保存为 .vcf 文件");
        fileChooser.setInitialFileName("contacts.vcf");
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("vCard 文件 (*.vcf)", "*.vcf")
        );
        return fileChooser.showSaveDialog(stage);
    }

    private void writeVcfFile(List<Contact> contacts, File file) throws IOException {
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
            for (Contact c : contacts) {
                writer.println("BEGIN:VCARD");
                writer.println("VERSION:3.0");

                // 姓名（FN 和 N）
                if (c.name != null && !c.name.isEmpty()) {
                    writer.println("FN:" + c.name);
                    String[] nameParts = c.name.split(" ", 2);
                    if (nameParts.length == 2) {
                        writer.println("N:" + nameParts[0] + ";" + nameParts[1] + ";;;");
                    } else {
                        writer.println("N:" + c.name + ";;;;");
                    }
                }

                // 电话号码（必须使用 TYPE=CELL 或 TYPE=WORK）
                if (c.phone != null && !c.phone.isEmpty()) {
                    // 推荐：添加类型标识，提高兼容性
                    writer.println("TEL;TYPE=CELL:" + c.phone); // 可改为 TYPE=WORK
                }

                // 单位（ORG）
                if (c.org != null && !c.org.isEmpty()) {
                    writer.println("ORG:" + c.org);
                }

                // 职务（TITLE）
                if (c.title != null && !c.title.isEmpty()) {
                    writer.println("TITLE:" + c.title);
                }

                // 性别（GENDER），vCard 3.0 支持
                if (c.gender != null && !c.gender.isEmpty()) {
                    writer.println("GENDER:" + c.gender); // 值为 M/F 或 male/female
                }

                // 唯一标识符（UID）
                writer.println("UID:" + UUID.randomUUID().toString().toUpperCase());

                writer.println("END:VCARD");
            }
        }
    }


    // 启用或禁用操作按钮
    private void enableActionButtons(boolean enable) {
        // 查找场景中的按钮并设置其禁用状态
        if (statusLabel.getScene() != null && statusLabel.getScene().getRoot() instanceof VBox) {
            VBox root = (VBox) statusLabel.getScene().getRoot();
            for (javafx.scene.Node node : root.getChildren()) {
                if (node instanceof Button && ((Button) node).getText().contains("打开")) {
                    ((Button) node).setDisable(!enable);
                }
            }
        }
    }

    // 打开保存文件的文件夹
    private void openSaveFolder() {
        if (lastSavedFile != null) {
            try {
                // 使用桌面功能打开文件所在文件夹
                java.awt.Desktop.getDesktop().open(lastSavedFile.getParentFile());
            } catch (Exception e) {
                statusLabel.setText("❌ 打开文件夹失败: " + e.getMessage());
                statusLabel.setStyle("-fx-text-fill: #F44336; -fx-font-size: 14px;");
            }
        }
    }

    // 打开保存的文件
    private void openSavedFile() {
        if (lastSavedFile != null) {
            try {
                // 使用桌面功能打开文件
                java.awt.Desktop.getDesktop().open(lastSavedFile);
            } catch (Exception e) {
                statusLabel.setText("❌ 打开文件失败: " + e.getMessage());
                statusLabel.setStyle("-fx-text-fill: #F44336; -fx-font-size: 14px;");
            }
        }
    }

    // 联系人模型类
    static class Contact {
        String name, phone, org, title, gender;

        public Contact(String name, String phone, String org, String title, String gender) {
            this.name = name != null ? name : "";
            this.phone = phone != null ? phone : "";
            this.org = org != null ? org : "";
            this.title = title != null ? title : "";
            this.gender = gender != null ? gender : "";
        }
    }

}